package com.movieproject.src;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.movieproject.daos.MovieDAO;
import com.movieproject.daos.QueueDAO;
import com.movieproject.daos.UserDAO;
import com.movieproject.dataobjects.Movie;
import com.movieproject.dataobjects.QueueRecord;
import com.movieproject.dataobjects.User;

@Transactional
@Controller
@RequestMapping(value = "/cart")
public class CartController {
	
	@Autowired
	private QueueDAO queueDAO;
	
	@Autowired
	private UserDAO userDAO;
	
	@Autowired
	private MovieDAO movieDAO;
	
//	@RequestMapping(value = "cart", method=RequestMethod.GET)
//	public String nineteenthpage() {
//		
//		return "cart";
//	}
	
	@RequestMapping(value = "cart", method={RequestMethod.POST})
	public String submitCart(HttpServletRequest request) {
		
			String[] JQueryArray = request.getParameterValues("queueIDs[]");
			List<Integer> queueIDs = new ArrayList<Integer>(); //LIST OF INT QueueIDs
			for (int i = 0; i < JQueryArray.length; i++) {
				queueIDs.add(Integer.parseInt(JQueryArray[i]));
			}
			
			int uID = (Integer) request.getSession().getAttribute("uName");
			
			List<Movie> movieList = new ArrayList<Movie>();
			User user = userDAO.getUser(uID);
			List<QueueRecord> userQueueList = queueDAO.getQueueListForUser(user); //LIST OF Queue Objects FOR USER
			


			

			for (Integer qID : queueIDs) {
				Iterator<QueueRecord> iter = userQueueList.iterator();
				while(iter.hasNext()){
					if(iter.next().getQueueID() == qID){
						iter.remove();
					}
				}
			}

			for (QueueRecord q : userQueueList) {
				movieList.add(q.getMovie());
			}
			
	
//		int uID = (Integer) request.getSession().getAttribute("uName");
//		User user = userDAO.getUser(uID);
//		
//		String[] JQueryArray = request.getParameterValues("queueIDs[]");
//		List<Integer> queueIDs = new ArrayList<Integer>();
//		for (int i = 0; i < JQueryArray.length; i++) {
//			queueIDs.add(Integer.parseInt(JQueryArray[i]));
//		}
//		
//		List<Movie> movieList = new ArrayList<Movie>();
//		for (Integer movID : queueIDs) {
//			movieList.add(movieDAO.getMovie(movID));
//		}
			
		queueDAO.updateUserQueue(user, movieList);
		
		
		return "cartSuccess";
	}

}
